<script setup>
import { ref } from 'vue'
import axios from "@/utils/request.js";
import {ElMessage, ElMessageBox} from 'element-plus'
import { onMounted } from "vue";
import { 
  matchAddService,
  matchSelectService,
  matchModifyService,
  matchDeleteService,
 } from '@/api/match';
 import { fileUploadService } from '@/api/file';
import  {MdPreview}  from 'md-editor-v3';
// import { MDEditor } from 'md-editor-v3';
// import {MdEditor} from 'md-editor-v3';
import 'md-editor-v3/lib/preview.css';
import moment from 'moment';
// 分页查询
const matchInfo = ref([])
const selectIds = Array


const handleSelectionChange = (selection) => {
  selectIds.value = selection.map(item => item.matchId)
}

//分页查询底部导航栏
const pageNo = ref(1)
const pageSize = ref(10)
const matchNameInput = ref()
const groupNameInput = ref()
const total = ref(0)

//页面加载的时候发送一次查询请求
onMounted(() => {
  load()
})
const handleCurrentChange = (val) => {
  pageNo.value = val
  load()
}
const handleSizeChange = (val) => {
  pageSize.value = val
  load()
}
//发送分页查询请求（包括搜索功能）
const load = async () => {
  const res = await matchSelectService(
    pageNo.value,pageSize.value,matchNameInput.value,groupNameInput.value
  )
  if(res.data.status === 'success'){
    matchInfo.value = res.data.data.list
    total.value = res.data.data.totalCount
  }else{
    ElMessage.error(res.data.info)
  }
}

/**
 * 添加比赛
 */
//定义模态窗口变量和表格对象
const introduceModel = ref(false)
const showAddModal = ref(false)
const matchInfoAddForm = ref({
  matchName: '',
  matchLevel: 1,
  matchTime: '',
  introduction: '',
  groupName: '',
  status: 0,
  cost: 1,
  auditStatus: 0,
})
//格式化日期并渲染在表格上
const formatDate = (dateString) => {
      const date = new Date(dateString);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，所以需要加1
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
  }
//打开模态窗口
const openAddModal = () => {
  //清空对象内容
  matchInfoAddForm.value = {
  matchName: '',
  matchLevel: 5,
  matchTime: '',
  introduction: '',
  groupName: '',
  status: 0,
  cost: 1,
  auditStatus: 0,
}
  showAddModal.value = true
}
//定义校验规则变量
const ruleFormRef = ref()
const ruleModifyFormRef = ref()
const rules = {
  matchName: [
    {required: true, message: '比赛名称不能为空', trigger: 'change'},
  ],
  matchTime: [
  {required: true, message: '比赛时间不能为空', trigger: 'change'},
  ]
}
//上传图片
const handleUploadImage = async(event, insertImage, files) => {
    // 拿到 files 之后上传到文件服务器，然后向编辑框中插入对应的内容
    const res = await fileUploadService(files[0])
    insertImage({
        url:
          axios.defaults.baseURL + "/file/downloadImage?filePath=" + res.data.data,
        desc: '图片描述',
        // width: '200px',
        // height: '200px',
    });
}
/**
 * 展示题目内容
 */
 const showIntroduction = ref(false)
const preview = ref(null)
const currentIntroduction = ref('')
const showIntroductionModal = (introduction) => {
  showIntroduction.value = true
  currentIntroduction.value = introduction
}
//发送添加比赛请求
const addMatchInfo = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
      matchInfoAddForm.value.matchTime = moment(matchInfoAddForm.value.matchTime).format("YYYY-MM-DD HH:mm:ss");
      // if(matchInfoAddForm.value.gender == '')userAddForm.value.gender = '0'
      const res = await matchAddService(matchInfoAddForm.value)
      if(res.data.status === 'success'){
        await load()
        ElMessage.success('添加比赛成功')
      }else{
        ElMessage.error(res.data.info)
      }
      showAddModal.value = false
    }
  })
}

/**
 * 修改比赛信息
 * @type {Ref<UnwrapRef<boolean>, UnwrapRef<boolean> | boolean>}
 */
//修改比赛（弹出模态窗口）
//定义模态窗口变量和表格对象
const modifyIntroduceModel = ref(false)
const showModifyModal = ref(false)
const matchForm = ref({
  matchName: '',
  matchLevel: '',
  matchTime: '',
  introduction: '',
  groupName: '',
  status: 0,
  cost: 1,
  auditStatus: 0,
})
const openModifyModal = (matchInfo) => {
  //将比赛数据渲染到模态窗口的表格上面
  matchForm.value.matchId = matchInfo.matchId
  matchForm.value.matchName = matchInfo.matchName
  matchForm.value.matchLevel = matchInfo.matchLevel
  matchForm.value.matchTime = matchInfo.matchTime
  matchForm.value.introduction = matchInfo.introduction
  matchForm.value.groupName = matchInfo.groupName
  matchForm.value.status = matchInfo.status
  matchForm.value.cost = matchInfo.cost
  matchForm.value.auditStatus = matchInfo.auditStatus
  //打开模态窗口
  showModifyModal.value = true
}

//发送修改比赛请求
const handleEdit = async (formEl) => {
  if (!formEl) return
  await formEl.validate(async(valid) => {
    if (valid) {
  const res = await matchModifyService(matchForm.value)
  if(res.data.status === 'success'){
    await load()
    ElMessage.success('修改比赛信息成功')
  }else{
    ElMessage.error(res.data.info)
  }
  showModifyModal.value = false
}
  })
};

/**
 * 删除比赛
 */
const openDeleteModal = (matchId) => {
  ElMessageBox.confirm(
    '确定要删除该比赛吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const matchIds = Array.of(matchId)
      const res = await matchDeleteService(matchIds)
      if(res.data.status === 'success'){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }else{
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      await load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}
/**
 * 批量删除比赛
 */
const opendeleteAllModal = () => {
  //非空判断
  if(selectIds.value == null){
    ElMessage.info('未选中任何一名比赛')
    return
  }
  if(selectIds.value != null && selectIds.value.length === 0){
    ElMessage.info('未选中任何一名比赛')
    return
  }
  //批量删除
  ElMessageBox.confirm(
    '确定要删除所有选中的比赛吗?',
    '警告',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
    .then(async() => {
      const res = await matchDeleteService(selectIds.value)
      if(res.data.status === 'success'){
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
      }else{
        ElMessage({
          type: 'error',
          message: '删除失败',
        })
      }
      load()
    })
    .catch(() => {
      ElMessage({
        type: 'info',
        message: '取消删除',
      })
    })
}

const getToken = () => {
  return localStorage.getItem('token')
}
</script>

<template>
<!--  模态窗口-->
<!--  修改成员信息模态窗口-->
  <div class="modify-modal" v-show="showModifyModal">
    <div class="modify-form">
      <div class="close-btn" @click="showModifyModal=false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">修改比赛信息</h1>
      <el-form :model="matchForm" ref="ruleModifyFormRef" :rules="rules" label-width="auto" style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="比赛名称" prop="matchName">
          <el-input v-model="matchForm.matchName" />
        </el-form-item>
        <el-form-item label="比赛级别">
          <el-radio-group v-model="matchForm.matchLevel">
            <el-radio :value="0">国际级</el-radio>
            <el-radio :value="1">国家级</el-radio>
            <el-radio :value="2">省级</el-radio>
            <el-radio :value="3">市级</el-radio>
            <el-radio :value="4">校级</el-radio>
            <el-radio :value="5">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="matchTime" label="比赛时间">
        <div class="demo-datetime-picker">
          <div class="block">
            <el-date-picker
              v-model="matchForm.matchTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </div>
      </el-form-item>
        <el-form-item label="比赛组委会">
          <el-input v-model="matchForm.groupName" />
        </el-form-item>
        <el-form-item label="比赛状态">
          <el-radio-group v-model="matchForm.status">
            <el-radio :value="0">报名中</el-radio>
            <el-radio :value="1">报名结束</el-radio>
            <el-radio :value="2">赛后</el-radio>
            <el-radio :value="3">成绩发布后</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报名费用">
          <el-input-number v-model="matchForm.cost" :min="1" :max="10000">
      <template #suffix>
        <span>元</span>
      </template>
    </el-input-number>
        </el-form-item>
        <el-form-item label="比赛介绍">
          <el-button @click="modifyIntroduceModel = true">修改内容</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="handleEdit(ruleModifyFormRef)">修改</el-button>
          <el-button @click="showModifyModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 修改比赛介绍模态窗口 -->
    <el-dialog
    v-model="modifyIntroduceModel"
    fullscreen
    top="40vh"
    width="70%"
    draggable
  >
    <span>比赛介绍</span>
    <template #footer>
      <div>
        <v-md-editor v-model="matchForm.introduction" height="400px" :include-level="[1, 2, 3, 4]" :disabled-menus="[]"
        @upload-image="handleUploadImage" />
      </div>
      <div class="dialog-footer">
        <el-button @click="modifyIntroduceModel = false">取消</el-button>
        <el-button type="primary" @click="modifyIntroduceModel = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
<!--  添加比赛模态窗口-->
  <div class="modify-modal" v-show="showAddModal">
    <div class="modify-form">
      <div class="close-btn" @click="showAddModal=false">&times;</div>
      <h1 style="text-align: center;font-size: 30px">添加比赛</h1>
      <el-form :model="matchInfoAddForm" ref="ruleFormRef" :rules="rules" label-width="auto" style="max-width: 600px;margin: auto;margin-top: 50px">
        <el-form-item label="比赛名称" prop="matchName">
          <el-input v-model="matchInfoAddForm.matchName" />
        </el-form-item>
        <el-form-item label="比赛级别">
          <el-radio-group v-model="matchInfoAddForm.matchLevel">
            <el-radio :value="0">国际级</el-radio>
            <el-radio :value="1">国家级</el-radio>
            <el-radio :value="2">省级</el-radio>
            <el-radio :value="3">市级</el-radio>
            <el-radio :value="4">校级</el-radio>
            <el-radio :value="5">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item prop="matchTime" label="比赛时间">
        <div class="demo-datetime-picker">
          <div class="block">
            <el-date-picker
              v-model="matchInfoAddForm.matchTime"
              type="datetime"
              format="YYYY-MM-DD HH:mm:ss"
            />
          </div>
        </div>
      </el-form-item>
        <el-form-item label="比赛组委会">
          <el-input v-model="matchInfoAddForm.groupName" />
        </el-form-item>
        <el-form-item label="比赛状态">
          <el-radio-group v-model="matchInfoAddForm.status">
            <el-radio :value="0">报名中</el-radio>
            <el-radio :value="1">报名结束</el-radio>
            <el-radio :value="2">赛后</el-radio>
            <el-radio :value="3">成绩发布后</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="报名费用">
          <el-input-number v-model="matchInfoAddForm.cost" :min="1" :max="10000">
      <template #suffix>
        <span>元</span>
      </template>
    </el-input-number>
        </el-form-item>
        <el-form-item label="比赛介绍">
          <el-button @click="introduceModel = true">填写内容</el-button>
        </el-form-item>
        <el-form-item style="float: right">
          <el-button type="primary" @click="addMatchInfo(ruleFormRef)">添加</el-button>
          <el-button @click="showAddModal=false">取消</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 填写比赛介绍模态窗口 -->
    <el-dialog
    v-model="introduceModel"
    fullscreen
    top="40vh"
    width="70%"
    draggable
  >
    <span>比赛介绍</span>
    <template #footer>
      <div>
        <v-md-editor v-model="matchInfoAddForm.introduction" height="400px" :include-level="[1, 2, 3, 4]" :disabled-menus="[]"
        @upload-image="handleUploadImage" />
      </div>
      <div class="dialog-footer">
        <el-button @click="introduceModel = false">取消</el-button>
        <el-button type="primary" @click="introduceModel = false">
          确定
        </el-button>
      </div>
    </template>
  </el-dialog>
  </div>
<!--    展示题目内容模态窗口-->
    <el-dialog v-model="showIntroduction" title="比赛介绍" width="800">
      
      <div style="height: 500px;">
        <span style="width: 100% !important;display: block;float: left;height: 500px;overflow-y: auto;">
          <MdPreview style="border: 1px solid;" :modelValue="currentIntroduction">
      </MdPreview >
            <!-- <v-md-editor :model-value="currentIntroduction" mode="preview" ref="preview"></v-md-editor> -->
        </span>
        
      
    </div>
    </el-dialog>

  <div>
<!--    功能按钮-->
    <el-card style="width: 34%;margin-bottom: 30px;float: left">
      <el-button @click="openAddModal" type="primary">添加比赛</el-button>
      <el-button @click="opendeleteAllModal" type="danger">批量删除</el-button>
    </el-card>
<!--    搜索框-->
    <el-card class="member-search">
      <span style="margin-left: 10px"><h2>比赛名称：</h2></span>
      <input v-model="matchNameInput" @keyup.enter.native="load">
      <span style="margin-left: 10px"><h2>比赛组委会：</h2></span>
      <input v-model="groupNameInput" @keyup.enter.native="load" style="border-right: none;">
      <el-button type="warning" @click="load">搜索</el-button>
    </el-card>
  </div>
  <div>
    <el-table
      ref="multipleTableRef"
      :data="matchInfo"
      stripe
      style="width: 100%;margin-top: 30px"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column property="matchName" label="比赛名称" width="110"/>
      <el-table-column property="matchTime" label="比赛时间" width="120">
        <template #default="scope">
          {{ formatDate(scope.row.matchTime) }}
        </template>
      </el-table-column>
      <el-table-column property="matchLevel" label="比赛级别" width="90" >
          <template #default="scope">
            <div v-if="scope.row.matchLevel === 0">国际级</div>
            <div v-if="scope.row.matchLevel === 1">国家级</div>
            <div v-if="scope.row.matchLevel === 2">省级</div>
            <div v-if="scope.row.matchLevel === 3">市级</div>
            <div v-if="scope.row.matchLevel === 4">校级</div>
            <div v-if="scope.row.matchLevel === 5">其他</div>
          </template>
        </el-table-column>
      <el-table-column property="groupName" label="比赛组委会" width="100" />
      <el-table-column property="status" label="比赛状态" width="100">
          <template #default="scope">
            <div v-if="scope.row.status === 0">报名中</div>
            <div v-if="scope.row.status === 1">报名结束</div>
            <div v-if="scope.row.status === 2">赛后</div>
            <div v-if="scope.row.status === 3">成绩发布后</div>
          </template>
        </el-table-column>
      <el-table-column property="auditStatus" label="审核状态" width="90">
          <template #default="scope">
            <div v-if="scope.row.auditStatus === 0">未通过</div>
            <div v-if="scope.row.auditStatus === 1">已通过</div>
          </template>
        </el-table-column>
      <el-table-column property="cost" label="报名费用(元)" width="120"/>
      <el-table-column property="createTime" label="创建时间" />
      <el-table-column property="updateTime" label="修改时间" />
      <el-table-column label="操作" width="220">
        <template #default="scope">
          <el-button size="small" type="success"
           @click="showIntroductionModal(scope.row.introduction)">
            详情
          </el-button>
          <el-button size="small" type="info" @click="openModifyModal(scope.row)">
            修改
          </el-button>
          <el-button
            size="small"
            type="danger"
            @click="openDeleteModal(scope.row.matchId)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
<!--    分页组件-->
    <el-card style="margin-top: 20px;float: right;">
      <div class="demo-pagination-block">
        <el-pagination
          v-model:current-page="pageNo"
          v-model:page-size="pageSize"
          :page-sizes="[2, 5, 10, 20]"
          size="large"
          :background="true"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>

  </div>
</template>


<style scoped>
/*模态窗口样式*/
.modify-modal{
  position: fixed;
  z-index: 10;
  left: 0;top: 0;
  width: 100%;height: 100%;
  background: black;
  opacity: 1;
}
/*模态窗口表格样式*/
.modify-form{
  background-color: #ffffff;
  margin: 5% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  z-index: 10;
  border-radius: 10%;
  width: 30%; /* Could be more or less, depending on screen size */
}
.close-btn {
  cursor: pointer;
  color: #000000;
  float: right;
  font-size: 28px;
  font-weight: bold;
}
/*搜索样式*/
.member-search{
  width: 64%;
  float: right
}
.member-search span{
  float: left;
}
.member-search input{
  float: left;
  height: 25px;
  border: solid 2px;
  margin-top: 2px;
}
/*表头样式*/
:deep() th.el-table__cell{
  color: black;
  font-size: 15px;
}
</style>
